<?php

namespace Admin\Controller;

use Admin\Logic\ContractLogic;
use App\Logic\WxPayDataLogic;
use Zend\Crypt\PublicKey\Rsa\PublicKey;

/** 	
 * 合同支付管理
 */
class ContractController extends CommonController 
{
	private $contract = null;
	private $wxpay = null;

	protected function _initialize() 
	{
		parent::_initialize();

		$this->contract = new ContractLogic();
		
		$this->wxpay = new WxPayDataLogic();
	}
	
	public function formAction()
	{	
		return $this->display();
	}
	
	public function editAction()
	{
		$id = I('get.id', 0, 'intval');
		
		$data = $this->contract->getEdit($id);
		
		$this->assign('data', $data);

		return $this->display();
	}

	public function detailAction()
	{
		$id = I('get.id', 0, 'intval');
		
		$data = $this->contract->getEdit($id);
		
		$this->assign('data', $data);

		return $this->display();
	}
	
	public function queryAction()
	{
		$query = array();
		
		$query = I('post.');
		
		$query_url = 'https://api.mch.weixin.qq.com/pay/orderquery';

		if( empty($query) === false )
		{
			$data = array(
					'appid' => 'wx2c5af222ae5d3860',
					'mch_id' => $query['mch_id'],
					'nonce_str' => generate_string('32'),
					'transaction_id' => $query['transaction_id'],
			);
				
			$sign = $this->wxpay->MakeSign($data);
				
			$data['sign'] = $sign;
				
			$data = $this->wxpay->ToXml($data);
				
			$result = $this->contract->responseByHttp($query_url,$data,'post');
				
			$ret = $this->wxpay->FromXml($result);
				
			$this->assign('data',$ret['data']);
			
			$this->assign('result',$result);
				
			$this->display('result');
		}
		else
		{
			return $this->display('query');
		}
	}

	public function notifyAction()
	{
		$data = $_POST['result'];
		
		$notify_url = 'http://api.test.com:81/app/contract/notify';
		
		$ret = $this->contract->responseByHttp($notify_url, $data, 'post');
		
		var_dump($ret);
	}

	public function saveAction()
	{
		$data = I('post.');

		if ($this->contract->updateContract($data) === false) 
		{
			return $this->error($this->contract->getError(), null, true);
		}
		
		return $this->success('操作成功', U('page'), true);
	}

	public function deleteAction() 
	{
		$id = I('get.id', 0, 'intval');

		if ($this->contract->deleteByPk($id) === false) 
		{
			return $this->error($this->contract->getError(), null, true);
		}

		return $this->success('删除成功');
	}

	public function pageAction() 
	{
		$page = null;
		
		$query = array();
		
		$query = I('get.');
	
		if( empty($query) === false )
		{
			$data = $this->contract->getPage($query, $page, $this->pageSize,$parameter='');
			
			$this->assign('data', $data);
			
			$this->assign('page', $page);
			
			return $this->display('page');
			
		}
		else
		{
			$data['status_list'] = $this->contract->getAllStatus();
			 
			$this->assign('data',$data);
			
			return $this->display('search');
		}
	}

	public function downloadAction()
	{
		$query = I('get.');

		$data = $this->contract->getDownLoad($query);

		$header_data = array(
				'合同编号',
				'微信支付单号',
				'姓名',
				'身份证号',
				'支付金额(元)',
				'支付时间',
				'贷款类型',
				'商品类型',
				'品牌',
				'总金额(元)',
				'首付金额(元)',
				'支付状态',
		);
		
		$this->export_csv_2($data,$header_data,sprintf('%s.csv',time()));
	}

	public function export_csv_2($data = [], $header_data = [], $file_name = '')
	{
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename='.$file_name);
		header('Cache-Control: max-age=0');
		$fp = fopen('php://output', 'a');
		if (!empty($header_data)) {
			foreach ($header_data as $key => $value) {
				$header_data[$key] = iconv('utf-8', 'gbk', $value);
			}
			fputcsv($fp, $header_data);
		}
		$num = 0;
		//每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
		$limit = 100000;
		//逐行取出数据，不浪费内存
		$count = count($data);
		if ($count > 0) {
			for ($i = 0; $i < $count; $i++) {
				$num++;
				//刷新一下输出buffer，防止由于数据过多造成问题
				if ($limit == $num) {
					ob_flush();
					flush();
					$num = 0;
				}
				$row = $data[$i];
				foreach ($row as $key => $value) {
					$row[$key] = iconv('utf-8', 'gbk', $value);
				}
				fputcsv($fp, $row);
			}
		}
		fclose($fp);
	}

}
